package fashionshop.gui.main.manage;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.border.TitledBorder;

import org.apache.commons.lang3.StringUtils;

import fashionshop.dao.CommonDao;
import fashionshop.dao.StoreManageDao;
import fashionshop.domain.Historical;
import fashionshop.domain.Store;
import fashionshop.gui.common.component.CallbackDialog;
import fashionshop.gui.common.component.ColumnConfig;
import fashionshop.gui.common.component.CommandToolBar.ToolBarType;
import fashionshop.gui.common.component.DataGridView;
import fashionshop.gui.common.component.DefaultCommandPanel;
import fashionshop.gui.common.constant.ModelConstants;
import fashionshop.gui.common.context.UserContext;
import fashionshop.gui.common.event.DialogSubmitListener;
import fashionshop.gui.common.model.StoreModelData;
import fashionshop.gui.common.util.MessageBoxUtil;
import fashionshop.gui.common.util.MessageBoxUtil.ConfirmDialogListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

@SuppressWarnings("serial")
public class StoreManagePanel extends DefaultCommandPanel {

	private static StoreManagePanel instance;
	private StoreManageDao storeManageDao = new StoreManageDao();
	private CommonDao commonDao = new CommonDao();
	private DataGridView<StoreModelData> gridItems;
	private AddOrEditStoreDialog storeDialog;
	
	private DialogSubmitListener<Store> addStoreDialogListener = new DialogSubmitListener<Store>() {
		
		@Override
		public void dialogSubmitCallback(CallbackDialog<Store> dialog) {
			Store newStore = new Store();
			dialog.populateData(newStore);
			newStore.setHistorical(new Historical(UserContext.getInstance().getEmployee(), new Date()));
			commonDao.saveEntity(newStore);
			gridItems.addRow(new StoreModelData(newStore));
			storeDialog.setVisible(false);
		}
	};
	
	private DialogSubmitListener<Store> editStoreDialogListener = new DialogSubmitListener<Store>() {
		
		@Override
		public void dialogSubmitCallback(CallbackDialog<Store> dialog) {
			Store store = gridItems.getSelectedModel().getEntity();
			dialog.populateData(store);
			store.getHistorical().setUpdatedBy(UserContext.getInstance().getEmployee());
			store.getHistorical().setUpdatedDate(new Date());
			commonDao.updateEntity(store);
			gridItems.updateCurrentRow(new StoreModelData(store));
			storeDialog.setVisible(false);
		}
	};
	private JTextField txtNameSearch;
	private JButton btnTm;
	
	@Override
	public void addPerformed() {
		storeDialog = AddOrEditStoreDialog.getInstance("Thêm cửa hàng", addStoreDialogListener);
		storeDialog.updateForm(null);
		storeDialog.setVisible(true);
	}
	
	@Override
	public void editPerformed() {
		if(gridItems.getSelectedRowCount() != 1){
			MessageBoxUtil.alert(StoreManagePanel.this, "Chọn cửa hàng cần xem.");
			return;
		}
		storeDialog = AddOrEditStoreDialog.getInstance("Thông tin cửa hàng", editStoreDialogListener);
		storeDialog.updateForm(gridItems.getSelectedModel().getEntity());
		storeDialog.setVisible(true);
	}
	
	@Override
	public void deletePerformed() {
		if(gridItems.getSelectedRowCount() != 1){
			MessageBoxUtil.alert(StoreManagePanel.this, "Chọn cửa hàng cần xóa.");
		}else{
			MessageBoxUtil.confirm(StoreManagePanel.this, "Bạn có chắc muốn xóa cửa hàng này?", new ConfirmDialogListener(){

				@Override
				public void confirmCallback(int option) {
					if(option == JOptionPane.OK_OPTION){
						StoreModelData model = gridItems.getSelectedModel();
						storeManageDao.deleteStore(model.getEntity().getId());
						gridItems.removeRow(model);
					}
				}
				
			});
		}
	}
	
	private void subInit(){
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();

		ColumnConfig column = new ColumnConfig(ModelConstants.STORE_NAME, "Tên cửa hàng");
		columns.add(column);

		column = new ColumnConfig(ModelConstants.STORE_ADDRESS, "Địa chỉ");
		columns.add(column);

		column = new ColumnConfig(ModelConstants.STORE_PHONE, "Số điện thoại");
		columns.add(column);
		
		gridItems.setColumnConfigs(columns);
	}
	
	private void searchStore(){
		List<Store> stores = storeManageDao.searchStore(StringUtils.trim(txtNameSearch.getText()));
		List<StoreModelData> storeModels = new ArrayList<StoreModelData>();
		for(Store store : stores){
			storeModels.add(new StoreModelData(store));
		}
		gridItems.setData(storeModels);
		if(gridItems.getRowCount() == 0){
			MessageBoxUtil.alert(StoreManagePanel.this, "Không tìm thấy kết quả phù hợp.");
		}
	}

	public static StoreManagePanel getInstance(){
		if(instance == null){
			instance = new StoreManagePanel();
		}
		return instance;
	}

	/**
	 * Create the panel.
	 */
	private StoreManagePanel() {
		addComponentListener(new ComponentAdapter() {
			@Override
			public void componentShown(ComponentEvent e) {
				refreshPerformed();
			}
		});
		initComponents();
		subInit();
	}
	private void initComponents() {

		JPanel topPanel = new JPanel();

		JLabel lblTitle = new JLabel("Quản lý hệ thống cửa hàng");
		topPanel.add(lblTitle);

		JPanel contentPanel = new JPanel();

		JPanel itemsPanel = new JPanel();
		itemsPanel.setBorder(new TitledBorder(null, "Danh s\u00E1ch c\u1EEDa h\u00E0ng", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		itemsPanel.setLayout(new BorderLayout(0, 0));

		JScrollPane scrollItems = new JScrollPane();
		scrollItems.setPreferredSize(new Dimension(24, 24));
		itemsPanel.add(scrollItems, BorderLayout.CENTER);

		this.gridItems = new DataGridView<StoreModelData>();
		scrollItems.setViewportView(this.gridItems);
		contentPanel.setLayout(new BorderLayout(0, 0));
		
		JPanel searchPanel = new JPanel();
		searchPanel.setBorder(new TitledBorder(null, "T\u00ECm ki\u1EBFm", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		contentPanel.add(searchPanel, BorderLayout.NORTH);
		
		JLabel lblSearchName = new JLabel("Tên cửa hàng:");
		
		this.txtNameSearch = new JTextField();
		this.txtNameSearch.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				if(e.getKeyCode() == KeyEvent.VK_ENTER){
					searchStore();
				}
			}
		});
		this.txtNameSearch.setColumns(10);
		
		this.btnTm = new JButton("Tìm");
		this.btnTm.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				searchStore();
			}
		});
		
		GroupLayout gl_searchPanel = new GroupLayout(searchPanel);
		gl_searchPanel.setHorizontalGroup(
			gl_searchPanel.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_searchPanel.createSequentialGroup()
					.addGap(57)
					.addComponent(lblSearchName)
					.addGap(18)
					.addComponent(this.txtNameSearch, GroupLayout.PREFERRED_SIZE, 267, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(this.btnTm)
					.addContainerGap(164, Short.MAX_VALUE))
		);
		gl_searchPanel.setVerticalGroup(
			gl_searchPanel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_searchPanel.createSequentialGroup()
					.addGroup(gl_searchPanel.createParallelGroup(Alignment.BASELINE)
						.addComponent(this.txtNameSearch, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(lblSearchName)
						.addComponent(this.btnTm))
					.addContainerGap(19, Short.MAX_VALUE))
		);
		searchPanel.setLayout(gl_searchPanel);
		contentPanel.add(itemsPanel, BorderLayout.CENTER);
		
		setLayout(new BorderLayout(0, 0));
		add(topPanel, BorderLayout.NORTH);
		add(contentPanel);
		
	}

	@Override
	public void refreshPerformed() {
		txtNameSearch.setText("");
		searchStore();
	}

	@Override
	public ToolBarType getCommandType() {
		return ToolBarType.ADD_EDIT_DELETE;
	}
}
